<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Utils\JWTHelper\JWTHelper;
use App\Utils\ResponseResult\JsonResult;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Ramsey\Uuid\Uuid;
use App\Utils\Common;

class AuthController extends Controller
{
    //注册
    public function register(Request $request): JsonResponse
    {
        $name=$request->input("name");
        $email=$request->input("email");
        $password=$request->input("password");
        //1.验证请求
        $validator = Validator::make($request->all(), [
            'name' => 'required |min:3 |max:20',
            'password' => 'required',
            'confirm_password' => 'required | same:password',
            'email' => 'required | email',
        ]);
        if ($validator->fails()) {
            return JsonResult::forBidden(null,"请求参数错误");
        }
        //2.验证用户是否存在（用户名，邮箱）
        $userCount = DB::table( table: "users")
            ->where(  "name", $name)
            ->orWhere(  "email", $email)
            ->count();
        if ($userCount > 0) {
            return JsonResult::forbidden(null,"账户/邮箱已存在");
        }
// 3.注册用户
        // 3.1 密码加密
        $password = Hash::make($password);
        // 3.2 保存用户信息
        $is_ok = DB::table("users")->insert([
            "name" => $name,
            "email" => $email,
            "password" => $password,
        ]);
        if (!$is_ok) {
            return JsonResult::forbidden(null, "账户注册失败");
        }
        //4.返回结果 ctrl+shift+↓ 整行下移
        return JsonResult::created(null,"账户注册成功");

    }
    //登录
    public function login(Request $request): JsonResponse
    {
        //1.验证请求
        $validator = Validator::make($request->all(), [
            'name' => 'required |min:3 |max:20',
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            return JsonResult::forBidden(null,"请求参数错误");
        }
        //2.验证用户账号和密码
        $name=$request->input("name");
        $password=$request->input("password");
        $hashedPassword=DB::table('users')
            ->where('name',$name)
            ->value('password');
        if ($hashedPassword === null) {
            return JsonResult::notFound(null,"用户不存在");
        }
        if (!Hash::check($password,$hashedPassword)) {
            return JsonResult::forbidden(null,"用户名或密码错误");
        }
        //3.生成token
        $user=DB::table("users")
            ->where('name',$name)
            ->select("id","name","email")
            ->first();
        $token=JWTHelper::createToken($user);
        //4.更新登录时间
        DB::table("users")
            ->where('name',$name)
            ->update(["login_at"=>now()]);
        //5.返回结果
        return JsonResult::created($token,"登录成功");

    }

    public function logout(): JsonResponse
    {
        $token = JWTHelper::forgetToken();
        return JsonResult::success($token, "退出成功");
    }

    /**
     * 修改用户信息(除了用户名，密码，邮箱，id，头像，status,created_at,login_at的其他信息)
     * @return JsonResponse
     */
    public function edit(Request $request): JsonResponse
    {
        //1.不需要验证请求，因为数据是可选项
        //直接获取请求参数
        $data=request()->only(["cellphone","gender","birth"]);
        $token = $request->header( key:"Authorization");
        $custom = JWTHelper::getCustom($token);
        if(!$custom){
            return JsonResult::unauthorized(  null,"token无效");
        }
        //2.更新用户信息
        $userId=$custom->id;
        DB::table("users")->where("id",$userId)
            ->update($data);
        return JsonResult::success(null, "编辑用户成功");
    }
    public function changePassword(Request $request): JsonResponse
    {
        //1.接收请求
        $oldPassword = $request->input("old_password");
        $newPassword = $request->input("new_password");
        $confirmPassword = $request->input("confirm_password");
//        2.验证请求
        $rules = [
            "old_password" => "required",
            "new_password" => "required|min:6",
            "confirm_password" => "required|same:new_password",
        ];
        //
        $message = [
            "old_password" => "内容不能为空",
            "new_password" => "内容不能为空",
            "confirm_password" => "两次密码输入不一致",
        ];
        $validator=Validator::make($request->all(),$rules,$message);
        if ($validator->fails()) {
            return JsonResult::forbidden(null, $validator->errors()->first());
        }
        //3.获取用户ID
        //3.1获取用户ID
        $token = $request->header( key:"Authorization");
        $custom = JWTHelper::getCustom($token);
        if(!$custom){
            return JsonResult::unauthorized(  null,"token无效");
        }
        $userId=$custom->id;
        //3.2获取用户密码
        $hashedPassword = DB::table("users")
            ->where("id",$userId)
            ->value("password");
        //3.3验证密码
        if(!Hash::check($oldPassword,$hashedPassword)){
            return JsonResult::forbidden(null,"原始密码错误");
        }
        //4.更新密码
        DB::table("users")
            ->where("id",$userId)
            ->update([
                "password" => Hash::make($newPassword)
            ]);
        return JsonResult::success(null,"密码修改成功");
    }

    public function avatar(Request $request): JsonResponse
    {
        //验证请求
        $validator = Validator::make($request->all(), [
            "avatar" => "required|file|mimes:jpg,png,jpeg,gif|max:200"
        ]);
        if ($validator -> fails()) {
          return JSonResult::forbidden(null,"上传文件错误");
        }
        //获取请求文件
        $file=$request->file("avatar");
        $fileExt=strtolower("." . $file->getClientOriginalExtension());
        $fileName = Uuid::uuid4() . ".$fileExt";
        $path="";
        $imagePath= $file->storeAs($path,$fileName,"avatar");
        if(!$imagePath){
            return JsonResult::forbidden(null,"头像上传失败");
        }
        $token = $request->header( key:"Authorization");
        $custom = JWTHelper::getCustom($token);
        if(!$custom){
            return JsonResult::unauthorized(  null,"未授权");
        }
        $userId=$custom->id;
        DB::table("users")
            ->where("id",$userId)
            ->update(["avatar" => $imagePath]);
        return JsonResult::success($path,"头像上传成功");

    }

    public function detail(Request $request): JsonResponse
    {
        $token = request()->header( key:"Authorization");
        $custom = JWTHelper::getCustom($token);
        if(!$custom){
            return JsonResult::unauthorized(  null,"未授权");
        }
        $userId=$custom->id;
        $user=DB::table("users")
            ->where("id",$userId)
            ->select("name","email","cellphone","gender","birth","avatar","created_at","login_at",)
            ->first();
        $user->avatar==$request->schemeAndHttpHost().
            "api/auth/getAvatar?avatar=".$user->avatar;
        return JsonResult::success($user,"获取用户信息成功");
    }
    public function getAvatar(Request $request)//: JsonResponse
    {

        $rules=[
            "avatar" => "required"
        ];
        if (validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        //获取请求参数（数据库的字段叫做avatar,其实是一个uuid）
        $avatar = $request->input("avatar");
        //获取头像的mime,目的按照这个mime的类型去生成对应的图片
        try {
            if (!Storage::disk("avatar")->exists($avatar)) {
                return JsonResult::forbidden(null,"获取图片失败");
            }
            $mime = Storage::disk("avatar")->mimeType($avatar);
            $image = Storage::disk("avatar")->get($avatar);
            return response($image,200,["Content-Type"=>$mime]);
        } catch (\Exception $e) {
            return JsonResult::forbidden(null,"获取图片失败");
        }
    }
    public function getPermissions(Request $request): JsonResponse
    {
        $token = request()->header( key:"Authorization");
        $custom = JWTHelper::getCustom($token);
        if(!$custom){
            return JsonResult::unauthorized(  null,"未授权");
        }
        $userId=$custom->id;
        // 查询用户的角色id
        $roleIds = DB::table("user_roles")
            ->where("user_id", $userId)
            ->pluck("role_id")
            ->toArray();
        // 查询角色的权限
        $permissionIds = DB::table("roles")
            ->whereIn("id", $roleIds)
            ->pluck("permissions")
            ->toArray();
        //权限id去重
        $permissionIds = join(",",$permissionIds);
        $permissionIds=array_unique(explode(",",$permissionIds));
        $permissions=DB::table("permissions")
            ->whereIn("id", $permissionIds)
            ->get();
        return JsonResult::success($permissions,"获取用户权限成功");
    }

    public function getMenus(Request $request): JsonResponse
    {
        // 根据token获取用户id
        $token = request()->header("Authorization");
        $custom = JWTHelper::getCustom($token);
        if (!$custom) {
            return JsonResult::unauthorized(null, "未授权");
        }
        $userId = $custom->id;
        // 查询用户的角色id
        $roleIds = DB::table("user_roles")
            ->where("user_id", $userId)
            ->pluck("role_id")
            ->toArray();
        // 查询角色的权限id
        $permissionIds = DB::table("roles")
            ->whereIn("id", $roleIds)
            ->pluck("permissions")
            ->toArray();
        // 权限id去重
        $permissionIds = join(",", $permissionIds);
        $permissionIds = array_unique(explode(",", $permissionIds));

        $AllPermissions = DB::table("permissions")
            ->where("menu", 1)
            ->get()
            ->toArray();
        $result = [];
        foreach ($permissionIds as $permissionId) {
            Common::findParents($AllPermissions, $permissionId, $result);
        }
        // 过滤菜单去重
        $result = collect($result)->unique('id')->values()->all();

        return JsonResult::success($result, "获取用户信息成功");
    }

    public function getPermissionsCount(Request $request): JsonResponse
    {
        $token = request()->header("Authorization");
        if (!$token) {
            return JsonResult::unauthorized(null, "token不存在");
        }
        
        $custom = JWTHelper::getCustom($token);
        if(!$custom){
            return JsonResult::unauthorized(null, "token无效");
        }
        
        $userId = $custom->id;
        // 查询用户的角色id
        $roleIds = DB::table("user_roles")
            ->where("user_id", $userId)
            ->pluck("role_id")
            ->toArray();
            
        if (empty($roleIds)) {
            return JsonResult::success(['count' => 0], "用户暂无权限");
        }
            
        // 查询角色的权限
        $permissionIds = DB::table("roles")
            ->whereIn("id", $roleIds)
            ->pluck("permissions")
            ->toArray();
            
        //权限id去重
        $permissionIds = join(",", $permissionIds);
        $permissionIds = array_unique(explode(",", $permissionIds));
        
        $count = count($permissionIds);
            
        return JsonResult::success(['count' => $count], "获取用户权限数量成功");
    }
}



